package org.kernelab.basis.socket;

import java.io.IOException;
import java.net.BindException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import org.kernelab.basis.Tools;

public class ConnectTester
{

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		String host = "59.79.47.156";

		int port = 25;

		new ConnectTester().connect(host, port);
	}

	public void connect(String host, int port)
	{
		SocketAddress remoteAddr = new InetSocketAddress(host, port);

		Socket socket = null;

		String result = "";

		try {

			long begin = System.currentTimeMillis();

			socket = new Socket();

			socket.connect(remoteAddr, 1000);

			long end = System.currentTimeMillis();

			result = (end - begin) + "ms";
		} catch (BindException e) {
			result = "Local address and port can't be binded.";
		} catch (UnknownHostException e) {
			result = "Unknown Host.";
		} catch (ConnectException e) {
			result = "Connection refused.";
		} catch (SocketTimeoutException e) {
			result = "TimeOut.";
		} catch (IOException e) {
			result = "Failure.";
		} finally {
			try {
				if (socket != null) {
					socket.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		Tools.debug(result);

	}
}
